/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ConsultaReserves.java
 *
 * Created on 21-nov-2011, 18:58:37
 */
package edu.uoc.tdp.pac4.only5.gui.client.panels.connexio;

import edu.uoc.tdp.pac4.only5.domain.Booking;
import edu.uoc.tdp.pac4.only5.domain.EnumStateBooking;
import edu.uoc.tdp.pac4.only5.domain.Payment;
import edu.uoc.tdp.pac4.only5.domain.Space;
import edu.uoc.tdp.pac4.only5.exceptions.EespaisDatabaseException;
import edu.uoc.tdp.pac4.only5.gui.client.ClientSession;
import edu.uoc.tdp.pac4.only5.gui.client.model.SpaceComboBoxModel;
import edu.uoc.tdp.pac4.only5.gui.client.panels.AbstractPanel;
import edu.uoc.tdp.pac4.only5.manager.BookingManager;
import edu.uoc.tdp.pac4.only5.manager.SpaceManager;
import edu.uoc.tdp.pac4.only5.tools.DateTool;
import java.rmi.RemoteException;
import edu.uoc.tdp.pac4.only5.gui.client.model.BookingTableModel;
import edu.uoc.tdp.pac4.only5.manager.PaymentManager;
import edu.uoc.tdp.pac4.only5.manager.ResourceManager;
import edu.uoc.tdp.pac4.only5.manager.UserManager;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.ListSelectionModel;

/**
 *
 * @author Gerard
 */
public class ConsultaReservesPanel extends AbstractPanel {

    private BookingManager bookingManager;
    private PaymentManager paymentManager;
    private SpaceManager spaceManager;
    private UserManager userManager;
    private ResourceManager resourceManager;
    private SpaceComboBoxModel spaceComboBoxModel;
    
    private JFrame jframe;
    
    private List<Booking> bookings;
    private Booking selectedBooking;
    
    private DetallReservaPanel panelDetall;

    public ConsultaReservesPanel(BookingManager bookingManager, SpaceManager spaceManager, PaymentManager paymentManager, UserManager userManager, ResourceManager resourceManager, JFrame jframe) {
        initComponents();
        this.spaceManager = spaceManager;
        this.bookingManager = bookingManager;
        this.paymentManager = paymentManager;
        this.resourceManager = resourceManager;
        this.userManager = userManager;
        this.jframe = jframe;
        fillTable();
        fillComboBox();
        tbl_bookings.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        setLabels();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tbl_bookings = new javax.swing.JTable();
        lblTitleConsultaReserves = new javax.swing.JLabel();
        btnShowDetails = new javax.swing.JButton();
        lblEspai = new javax.swing.JLabel();
        cmbSpaces = new javax.swing.JComboBox();
        lblStartTime = new javax.swing.JLabel();
        lblEndTime = new javax.swing.JLabel();
        btnBuscar = new javax.swing.JButton();
        chkCancel = new javax.swing.JCheckBox();
        txtRecarrec = new javax.swing.JTextField();
        lblRecarrec = new javax.swing.JLabel();
        lblMotiuCancelacio = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtObs = new javax.swing.JTextArea();
        btnCancelar = new javax.swing.JButton();
        txtDateEnd1 = new javax.swing.JTextField();
        txtDateStart1 = new javax.swing.JTextField();

        setPreferredSize(new java.awt.Dimension(800, 600));

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tbl_bookings.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        tbl_bookings.setName("tbl_bookings"); // NOI18N
        tbl_bookings.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbl_bookingsMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbl_bookings);

        lblTitleConsultaReserves.setFont(new java.awt.Font("Lucida Grande", 0, 18));
        lblTitleConsultaReserves.setText("Consulta de Reserves");
        lblTitleConsultaReserves.setName("lbl_TitleConsultaReservesPanel"); // NOI18N

        btnShowDetails.setText("Veure detall reserva");
        btnShowDetails.setEnabled(false);
        btnShowDetails.setName("btnShowDetails"); // NOI18N
        btnShowDetails.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnShowDetailsActionPerformed(evt);
            }
        });

        lblEspai.setText("Espai");
        lblEspai.setName("lblEspai"); // NOI18N

        cmbSpaces.setName("cmbSpaces"); // NOI18N

        lblStartTime.setText("Data Inici");
        lblStartTime.setName("lblStartTime"); // NOI18N

        lblEndTime.setText("Data Fi");
        lblEndTime.setName("lblEndTime"); // NOI18N

        btnBuscar.setText("Buscar");
        btnBuscar.setName("btnBuscar"); // NOI18N
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        chkCancel.setText("Vol cancelar la reserva?");
        chkCancel.setEnabled(false);
        chkCancel.setName("chkCancel"); // NOI18N
        chkCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkCancelActionPerformed(evt);
            }
        });

        txtRecarrec.setEnabled(false);
        txtRecarrec.setName("txtRecarrec"); // NOI18N

        lblRecarrec.setText("Recàrrec");
        lblRecarrec.setName("lblRecarrec"); // NOI18N

        lblMotiuCancelacio.setText("Motiu Cancel·lació:");
        lblMotiuCancelacio.setName("lblMotiuCancelacio"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        txtObs.setColumns(20);
        txtObs.setRows(5);
        txtObs.setEnabled(false);
        txtObs.setName("txtObs"); // NOI18N
        jScrollPane2.setViewportView(txtObs);

        btnCancelar.setText("Cancel·lar");
        btnCancelar.setName("btnCancelar"); // NOI18N
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        txtDateEnd1.setName("txtDateEnd1"); // NOI18N

        txtDateStart1.setName("txtDateStart1"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 760, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGap(24, 24, 24)
                        .addComponent(lblEspai)
                        .addGap(11, 11, 11)
                        .addComponent(cmbSpaces, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(lblStartTime)
                        .addGap(18, 18, 18)
                        .addComponent(txtDateStart1, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 53, Short.MAX_VALUE)
                        .addComponent(lblEndTime)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtDateEnd1, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnBuscar)
                        .addGap(44, 44, 44))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblTitleConsultaReserves)
                        .addContainerGap(596, Short.MAX_VALUE))))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(616, Short.MAX_VALUE)
                .addComponent(btnShowDetails)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(43, 43, 43)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(chkCancel)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lblRecarrec)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txtRecarrec, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblMotiuCancelacio))
                            .addComponent(btnCancelar))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 283, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(192, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblTitleConsultaReserves)
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblEspai)
                    .addComponent(cmbSpaces, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblStartTime)
                    .addComponent(txtDateStart1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtDateEnd1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnBuscar)
                    .addComponent(lblEndTime))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnShowDetails)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(chkCancel)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtRecarrec, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblRecarrec)
                            .addComponent(lblMotiuCancelacio))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnCancelar))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(246, 246, 246))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnShowDetailsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnShowDetailsActionPerformed
        Booking booking = bookings.get(tbl_bookings.getSelectedRow());
        panelDetall = new DetallReservaPanel(userManager, paymentManager, spaceManager, resourceManager, booking);
        panelDetall.setVisible(true);
        this.setVisible(false);
        jframe.add(panelDetall);
        jframe.pack();
    }//GEN-LAST:event_btnShowDetailsActionPerformed

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        fillTable();
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void tbl_bookingsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbl_bookingsMouseClicked
        selectedBooking = bookings.get(tbl_bookings.getSelectedRow());
        boolean selected = selectedBooking != null && !EnumStateBooking.CANCELADA.name().equals(selectedBooking.getStatus()) && (selectedBooking.getEndTime().after(new Date()));
        chkCancel.setEnabled(selected);
        txtObs.setEnabled(selected);
        btnShowDetails.setEnabled(true);
    }//GEN-LAST:event_tbl_bookingsMouseClicked

    private void chkCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkCancelActionPerformed
        try {
            Payment payment = paymentManager.getPaymentbyId(selectedBooking.getId());
            int result = bookingManager.calculaRecargo(selectedBooking, payment);
            txtRecarrec.setText(Integer.toString(result));
        } catch (RemoteException ex) {
            showErrorMessageDialog(this, "error.generic.rmi");
        } catch(EespaisDatabaseException ex){
            showErrorMessageDialog(this, "error.generic.databaseerror");
        } 
    }//GEN-LAST:event_chkCancelActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        try {
            paymentManager.UpdatePaymentBooking(selectedBooking.getId(), Integer.parseInt(txtRecarrec.getText()));
            bookingManager.UpdateCancelBooking(selectedBooking.getId(), txtObs.getText(), ClientSession.getInstance().getUser().getUserId());
            showMessageDialog(this, "aules.cancelok");
            fillTable();
            btnShowDetails.setEnabled(false);
        } catch (RemoteException ex) {
            showErrorMessageDialog(this, "error.generic.rmi");
        } catch(EespaisDatabaseException ex){
            showErrorMessageDialog(this, "error.generic.databaseerror");
        } 
    }//GEN-LAST:event_btnCancelarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnShowDetails;
    private javax.swing.JCheckBox chkCancel;
    private javax.swing.JComboBox cmbSpaces;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblEndTime;
    private javax.swing.JLabel lblEspai;
    private javax.swing.JLabel lblMotiuCancelacio;
    private javax.swing.JLabel lblRecarrec;
    private javax.swing.JLabel lblStartTime;
    private javax.swing.JLabel lblTitleConsultaReserves;
    private javax.swing.JTable tbl_bookings;
    private javax.swing.JTextField txtDateEnd1;
    private javax.swing.JTextField txtDateStart1;
    private javax.swing.JTextArea txtObs;
    private javax.swing.JTextField txtRecarrec;
    // End of variables declaration//GEN-END:variables

    @Override
    protected void setLabels() {
        lblEndTime.setText(getText("consultareserva.endtime"));
        lblEspai.setText(getText("consultareserva.espai"));
        lblMotiuCancelacio.setText(getText("consultareserva.motiu"));
        lblRecarrec.setText(getText("consultareserva.recarrec"));
        lblStartTime.setText(getText("consultareserva.starttime"));
        lblTitleConsultaReserves.setText(getText("consultareserva.title"));
        
        btnBuscar.setText(getText("consultareserva.buscar"));
        btnCancelar.setText(getText("consultareserva.cancelar"));
        btnShowDetails.setText(getText("consultareserva.showdetails"));

        chkCancel.setText(getText("consultareserva.checkcancel"));
    }

    private void fillTable() {
        Date from = null;
        Date to = null;
        try {
            
            if(!txtDateStart1.getText().trim().equals("")){
                from = DateTool.getInstance().convertDateToString(txtDateStart1.getText());
            }
            if(!txtDateEnd1.getText().trim().equals("")){
                to = DateTool.getInstance().convertDateToString(txtDateEnd1.getText());    
            }

        } catch (ParseException ex) {
            Logger.getLogger(ConsultaReservesPanel.class.getName()).log(Level.SEVERE, null, ex);
            showErrorMessageDialog(this, "error.incorrectdate");
        }

        Integer space = null;

        if (cmbSpaces != null && cmbSpaces.getSelectedItem() != null) {
            space = ((Space) cmbSpaces.getSelectedItem()).getSpaceId();
        }


        try {
            bookings = bookingManager.getBookings(ClientSession.getInstance().getUser().getUserId(), space, from, to);
        } catch (RemoteException ex) {
            showErrorMessageDialog(this, "error.generic.rmi");
        } catch(EespaisDatabaseException ex){
            showErrorMessageDialog(this, "error.generic.databaseerror");
        } 
        String[] columns = {"table.booking.id", "table.booking.userId", "table.booking.startTime", "table.booking.endTime", "table.booking.pax", "table.booking.status", "table.booking.creationTime", "table.booking.cancelTime", "table.booking.cancelUser", "table.booking.recordDate"};

        tbl_bookings.setModel(new BookingTableModel(bookings, columns));
        setTableHeaders(columns, tbl_bookings);
    }

    private void fillComboBox() {
        try {
            spaceComboBoxModel = new SpaceComboBoxModel(spaceManager.getSpaces());
            cmbSpaces.setModel(spaceComboBoxModel);
        } catch (RemoteException ex) {
            showErrorMessageDialog(this, "error.generic.rmi");
        } catch(EespaisDatabaseException ex){
            showErrorMessageDialog(this, "error.generic.databaseerror");
        } 
    }
}
